package com.shankungfu.adapter;

import java.util.List;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

public class MyPagerAdapter extends PagerAdapter {
	public List<View> mListViews;

	public MyPagerAdapter(List<View> mListViews) {
		this.mListViews = mListViews;
	}

	@Override
	public void destroyItem(View container, int position, Object object) {
		((ViewGroup) container).removeView(mListViews.get(position));
	}

	@Override
	public Object instantiateItem(View container, int position) {
		try {
			if (mListViews.get(position).getParent() == null)
				((ViewPager) container).addView(mListViews.get(position), 0);
			else {
				// 很难理解新添加进来的view会自动绑定一个父类，由于一个儿子view不能与两个父类相关，所以得解绑
				// 不这样做否则会产生 viewpager java.lang.IllegalStateException: The
				// specified child already has a parent. You must call
				// removeView() on the child's parent first.
				// 还有一种方法是viewPager.setOffscreenPageLimit(3); 这种方法不用判断parent
				// 是不是已经存在，但多余的listview不能被destroy
				((ViewGroup) mListViews.get(position).getParent())
						.removeView(mListViews.get(position));
				((ViewPager) container).addView(mListViews.get(position), 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mListViews.get(position);
	}

	@Override
	public int getCount() {
		return mListViews != null ? mListViews.size() : 0;
	}

	@Override
	public boolean isViewFromObject(View v, Object arg1) {
		return v == arg1;
	}

}
